package com.changpay.zywy.ui.fragment.qudao

import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.changpay.zywy.R
import com.changpay.zywy.adapter.MyPartentAdapter
import com.changpay.zywy.adapter.MyShopAdapter
import com.changpay.zywy.base.BaseFragment
import com.changpay.zywy.base.IView
import com.changpay.zywy.ext.sss
import com.changpay.zywy.http.RetrofitHelper

import com.changpay.zywy.bean.MyPartent
import com.changpay.zywy.bean.MyShopBean
import com.changpay.zywy.ext.showToast
import com.changpay.zywy.ui.activity.partent.PartnerMachineControlActivity
import com.changpay.zywy.ui.activity.partent.QuDaoActivity
import com.changpay.zywy.ui.activity.partent.ShopShareProfitActivity
import com.changpay.zywy.wight.CustomLoadMoreView
import com.changpay.zywy.wight.SpaceItemDecoration
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import kotlinx.android.synthetic.main.fragment_refresh_layout.swipeRefreshLayout


class QuDaoFragment : BaseFragment(), IView {


    override fun showLoading() {

    }

    override fun hideLoading() {
        swipeRefreshLayout?.isRefreshing = false

    }

    override fun showDefaultMsg(msg: String) {

    }

    override fun showMsg(msg: String) {

    }

    override fun showError(errorMsg: String) {

    }

    private var searchKey = ""
    private var position: Int = 0  // 当前viewPage的位置
    private lateinit var type: String
    private var page = 1
    private val pagesize = 10
    private var isFirst = true
    private var isGoToOther = true


    companion object {
        fun getInstance(instanceType: Int): QuDaoFragment {
            val bundle = Bundle()
            bundle.putInt("position", instanceType)
            val fragment = QuDaoFragment()
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun attachLayoutRes(): Int = R.layout.fragment_refresh_layout

    override fun lazyLoad() {
        holder?.showLoading()
        loadData()
    }

    override fun initView(view: View) {
        position = arguments?.getInt("position") ?: 0
        type = if (position == 1) "0" else "1"
        swipeRefreshLayout.isEnabled = false
        initRecyclerView()
    }

    /**
     * datas
     */
    private val datas_one = mutableListOf<MyShopBean.DataBean>()

    /**
     * datas
     */
    private val datas_two = mutableListOf<MyPartent.ListBean>()

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        this.let {
            SpaceItemDecoration(context!!)
        }
    }

    /**
     * Adapter
     */
    private val mAdapter_one: MyShopAdapter by lazy {
        MyShopAdapter(context, datas_one)
    }

    /**
     * Adapter
     */
    private val mAdapter_two: MyPartentAdapter by lazy {
        MyPartentAdapter(context, datas_two)
    }


    /**
     * LinearLayoutManager
     */
    private val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(context)
    }

    /**
     * LoadMoreListener
     */
    private val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        when (position) {
            0 -> {
                page = mAdapter_one.data.size / pagesize + 1
                loadData()
            }
            1 -> {
                page = mAdapter_two.data.size / pagesize + 1
                loadData()
            }
        }

    }

    private fun loadData() {
        if (position == 0) {
            val param = hashMapOf<String, String>()
            param["key"] = token
            param["sn_code"] = searchKey
            param["version"] = "2.0"
            param["page"] = page.toString()
            RetrofitHelper.service.listOfMyBusiness(param).sss(this)
            {
                holder?.showLoadSuccess()
                mAdapter_one.run {
                    addData(it.result.data)
                    val size = it.result.data.size
                    if (size < 10) {
                        loadMoreEnd(true)
                    } else {
                        loadMoreComplete()
                    }
                }
                val act = activity as QuDaoActivity
                act.changeTabTitle(position, it.result.total.toString())
            }
        } else {
            val param = hashMapOf<String, String>()
            param["key"] = token
            param["search_key"] = searchKey
            param["version"] = "2.0"
            param["page"] = page.toString()
            RetrofitHelper.service.my_partners_list(param).sss(this)
            {
                holder?.showLoadSuccess()
                mAdapter_two.run {
                    addData(it.result.list)
                    val size = it.result.list.size
                    if (size < 10) {
                        loadMoreEnd(true)
                    } else {
                        loadMoreComplete()
                    }
                }
                val act = activity
                (act as QuDaoActivity).changeTabTitle(position, it.result.total_count.toString())

            }
        }
    }


    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        when (this.position) {
            0 -> if (datas_one.size != 0) {
                val data = datas_one[position]
                Intent(activity, ShopShareProfitActivity::class.java).run {
                    putExtra("goods_id", data.goods_id.toString())
                    putExtra("sn_code", data.sn_code)
                    startActivity(this)
                }
            }
            1 -> if (datas_two.size != 0) {
                val data = datas_two[position]
                isGoToOther = false
                Intent(activity, PartnerMachineControlActivity::class.java).run {
                    putExtra("others_member_id", data.member_id.toString())
                    startActivity(this)
                }
            }
        }
    }

    /**
     * ItemChildClickListener
     */
    private val onItemChildClickListener = BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
        when (this.position) {
        }
    }


    private fun initRecyclerView() {
        recyclerView.run {
            layoutManager = linearLayoutManager
            when (position) {
                0 -> adapter = mAdapter_one
                1 -> adapter = mAdapter_two
            }
            itemAnimator = DefaultItemAnimator()
//            recyclerViewItemDecoration.let { addItemDecoration(it) }
        }


        val adapter = when (position) {
            0 -> mAdapter_one
            1 -> mAdapter_two
            else -> mAdapter_one
        }
        adapter.run {
            bindToRecyclerView(recyclerView)
            setOnLoadMoreListener(onRequestLoadMoreListener, recyclerView)
            setLoadMoreView(CustomLoadMoreView())
            onItemClickListener = this@QuDaoFragment.onItemClickListener
            onItemChildClickListener = this@QuDaoFragment.onItemChildClickListener
            setEmptyView(R.layout.fragment_empty_layout)
        }


    }


    fun searchData(searchKey: String) {
        this.searchKey = searchKey
        page = 1
        if (position == 0) {
            datas_one.clear()
        } else {
            datas_two.clear()
        }
        loadData()
    }


    // 用于配置政策后刷新数据
    override fun onResume() {
        super.onResume()
        if (isFirst && position == 1 && isGoToOther) {
            isFirst = false
        } else if (position == 1 && isGoToOther) {
            val param = hashMapOf<String, String>()
            param["key"] = token
            param["search_key"] = searchKey
            param["version"] = "2.0"
            param["page"] = "1"
            param["pagesize"] = mAdapter_two.data.size.toString()
            datas_two.clear()
            mAdapter_two.notifyDataSetChanged()
            RetrofitHelper.service.my_partners_list(param).sss(this)
            {
                mAdapter_two.run {
                    addData(it.result.list)
                }
            }
        } else {
            isGoToOther = true
        }
    }
}






